package com.mm.cloth.api;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.mm.cloth.model.request.ClothesListRequest;
import com.mm.cloth.model.request.LoginRequest;
import com.mm.cloth.model.response.ApiResponse;
import com.mm.cloth.model.response.ClothesListResponse;
import com.mm.cloth.model.response.LoginResponse;
import com.mm.cloth.model.response.SystemConfigResponse;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * API管理器
 * 封装所有API调用，提供统一的接口
 */
public class ApiManager {
    
    private static final String TAG = "ApiManager";
    private static final Gson gson = new Gson();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    /**
     * 获取系统配置信息（用于版本更新检查）
     * @param callback 回调接口
     */
    public static void getSystemConfig(final ApiCallback<SystemConfigResponse> callback) {
        // 构建请求
        String url = ApiClient.getApiUrl("/api/system/config");
        Log.d(TAG, "发起请求: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        
        // 发送请求
        ApiClient.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 记录错误日志
                Log.e(TAG, "请求失败: " + e.getMessage(), e);
                // 在主线程中回调失败
                mainHandler.post(() -> callback.onFailure(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    // 获取响应内容
                    String responseBody = response.body().string();
                    Log.d(TAG, "收到响应: " + responseBody);
                    
                    // 解析JSON
                    ApiResponse<SystemConfigResponse> apiResponse = parseResponse(responseBody, SystemConfigResponse.class);
                    
                    // 在主线程中回调结果
                    if (apiResponse != null) {
                        if (apiResponse.isSuccess()) {
                            Log.d(TAG, "请求成功: " + gson.toJson(apiResponse.getData()));
                            mainHandler.post(() -> callback.onSuccess(apiResponse.getData()));
                        } else {
                            Log.w(TAG, "请求失败: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                            mainHandler.post(() -> callback.onFailure(apiResponse.getCode(), apiResponse.getMessage()));
                        }
                    } else {
                        Log.e(TAG, "解析响应失败");
                        mainHandler.post(() -> callback.onFailure(response.code(), "解析响应失败"));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理响应失败: " + e.getMessage(), e);
                    mainHandler.post(() -> callback.onFailure(response.code(), "处理响应失败: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param callback 回调接口
     */
    public static void login(String username, String password, final ApiCallback<LoginResponse> callback) {
        // 创建登录请求对象
        LoginRequest loginRequest = new LoginRequest(username, password);
        
        // 将请求对象转换为JSON
        String jsonBody = gson.toJson(loginRequest);
        
        // 构建请求
        String url = ApiClient.getApiUrl("/api/user/login");
        Log.d(TAG, "发起登录请求: " + url);
        
        RequestBody body = RequestBody.create(jsonBody, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        
        // 发送请求
        ApiClient.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 记录错误日志
                Log.e(TAG, "登录请求失败: " + e.getMessage(), e);
                // 在主线程中回调失败
                mainHandler.post(() -> callback.onFailure(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    // 获取响应内容
                    String responseBody = response.body().string();
                    Log.d(TAG, "登录响应: " + responseBody);
                    
                    // 解析JSON
                    ApiResponse<LoginResponse> apiResponse = parseResponse(responseBody, LoginResponse.class);
                    
                    // 在主线程中回调结果
                    if (apiResponse != null) {
                        if (apiResponse.isSuccess()) {
                            Log.d(TAG, "登录成功: " + gson.toJson(apiResponse.getData()));
                            mainHandler.post(() -> callback.onSuccess(apiResponse.getData()));
                        } else {
                            Log.w(TAG, "登录失败: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                            mainHandler.post(() -> callback.onFailure(apiResponse.getCode(), apiResponse.getMessage()));
                        }
                    } else {
                        Log.e(TAG, "解析登录响应失败");
                        mainHandler.post(() -> callback.onFailure(response.code(), "解析响应失败"));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理登录响应失败: " + e.getMessage(), e);
                    mainHandler.post(() -> callback.onFailure(response.code(), "处理响应失败: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 获取衣物列表
     * @param request 请求参数
     * @param token 认证令牌
     * @param callback 回调接口
     */
    public static void getClothes(ClothesListRequest request, String token, final ApiCallback<ClothesListResponse> callback) {
        // 构建URL和查询参数
        HttpUrl.Builder urlBuilder = HttpUrl.parse(ApiClient.getApiUrl("/api/clothes/list")).newBuilder();
        
        // 添加查询参数
        urlBuilder.addQueryParameter("page", String.valueOf(request.getPage()));
        urlBuilder.addQueryParameter("pageSize", String.valueOf(request.getPageSize()));
        
        // 添加可选参数
        if (request.getCategoryId() != null && request.getCategoryId() > 0) {
            urlBuilder.addQueryParameter("categoryId", String.valueOf(request.getCategoryId()));
        }
        
        if (request.getSeason() != null && !request.getSeason().equals("全部")) {
            urlBuilder.addQueryParameter("season", request.getSeason());
        }
        
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            urlBuilder.addQueryParameter("keyword", request.getKeyword());
        }
        
        if (request.getSortBy() != null && !request.getSortBy().isEmpty()) {
            urlBuilder.addQueryParameter("sortBy", request.getSortBy());
            
            if (request.getSortOrder() != null && !request.getSortOrder().isEmpty()) {
                urlBuilder.addQueryParameter("sortOrder", request.getSortOrder());
            }
        }
        
        String url = urlBuilder.build().toString();
        Log.d(TAG, "发起获取衣物列表请求: " + url);
        
        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .get();
        
        // 添加认证头
        if (token != null && !token.isEmpty()) {
            requestBuilder.addHeader("Authorization", "Bearer " + token);
        }
        
        Request request2 = requestBuilder.build();
        
        // 发送请求
        ApiClient.getInstance().getOkHttpClient().newCall(request2).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 记录错误日志
                Log.e(TAG, "获取衣物列表请求失败: " + e.getMessage(), e);
                // 在主线程中回调失败
                mainHandler.post(() -> callback.onFailure(500, "网络请求失败: " + e.getMessage()));
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    // 获取响应内容
                    String responseBody = response.body().string();
                    Log.d(TAG, "衣物列表响应: " + responseBody);
                    
                    // 解析JSON
                    ApiResponse<ClothesListResponse> apiResponse = parseResponse(responseBody, ClothesListResponse.class);
                    
                    // 在主线程中回调结果
                    if (apiResponse != null) {
                        if (apiResponse.isSuccess()) {
                            Log.d(TAG, "获取衣物列表成功: " + gson.toJson(apiResponse.getData()));
                            mainHandler.post(() -> callback.onSuccess(apiResponse.getData()));
                        } else {
                            Log.w(TAG, "获取衣物列表失败: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                            mainHandler.post(() -> callback.onFailure(apiResponse.getCode(), apiResponse.getMessage()));
                        }
                    } else {
                        Log.e(TAG, "解析衣物列表响应失败");
                        mainHandler.post(() -> callback.onFailure(response.code(), "解析响应失败"));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理衣物列表响应失败: " + e.getMessage(), e);
                    mainHandler.post(() -> callback.onFailure(response.code(), "处理响应失败: " + e.getMessage()));
                }
            }
        });
    }
    
    /**
     * 解析API响应
     * @param responseBody 响应内容
     * @param dataClass 数据类型
     * @param <T> 数据泛型
     * @return API响应对象
     */
    private static <T> ApiResponse<T> parseResponse(String responseBody, Class<T> dataClass) {
        try {
            // 创建ApiResponse对象
            ApiResponse<T> apiResponse = new ApiResponse<>();
            
            // 解析JSON
            JSONObject jsonObject = new JSONObject(responseBody);
            apiResponse.setCode(jsonObject.getInt("code"));
            apiResponse.setMessage(jsonObject.getString("message"));
            
            // 解析data字段
            if (!jsonObject.isNull("data")) {
                String dataJson = jsonObject.getJSONObject("data").toString();
                T data = gson.fromJson(dataJson, dataClass);
                apiResponse.setData(data);
            }
            
            return apiResponse;
        } catch (Exception e) {
            Log.e(TAG, "解析JSON失败: " + e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * API回调接口
     * @param <T> 响应数据类型
     */
    public interface ApiCallback<T> {
        /**
         * 请求成功回调
         * @param data 响应数据
         */
        void onSuccess(T data);
        
        /**
         * 请求失败回调
         * @param code 错误码
         * @param message 错误信息
         */
        void onFailure(int code, String message);
    }
} 